package in.srain.cube.util;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.mcxiaoke.packer.helper.PackerNg;

public class UTUtil {

    private static final String CHANNEL_DEFAULT = "default";

    private static UTUtil sInstance;

    private String mChannel;
    private DataTrack mDataTrack;
    private Context mContext;

    private UTUtil() {
    }

    public synchronized static UTUtil getInstance() {
        if (sInstance == null) {
            sInstance = new UTUtil();
        }
        return sInstance;
    }

    public void setContext(Context context) {
        mContext = context.getApplicationContext();
    }

    public void init(DataTrack dataTrack) {
        String channel = PackerNg.getChannel(mContext);
        mChannel = !TextUtils.isEmpty(channel) ? channel : CHANNEL_DEFAULT;

        mDataTrack = dataTrack;
        mDataTrack.onApplicationCreate(mChannel, mContext);
    }

    public void onPause(Context context) {
    }

    public void onResume(Activity activity) {
    }

    public void flushEvent(@NonNull String keys) {
        logEvent(keys, new Bundle());
        flushLogEvent();
    }

    public void flushEvent(@NonNull String keys, @NonNull Bundle properties) {
        logEvent(keys, properties);
        flushLogEvent();
    }

    public void logEvent(@NonNull String keys) {
        logEvent(keys, new Bundle());
    }

    public void logEvent(@NonNull String key, @NonNull Bundle properties) {
        mDataTrack.logEvent(key, properties);
    }

    public void setUserId(String uid) {
        mDataTrack.setUserId(uid);
    }

    public void setUserProperty(@NonNull String property, @Nullable String value) {
        mDataTrack.setUserProperty(property, value);
    }

    public void setSuperProperty(@NonNull String property, @Nullable String value) {
        mDataTrack.setSuperProperty(property, value);
    }

    public <T> T getABTestValue(@NonNull String property, @Nullable T t) {
        return mDataTrack.getABTestValue(property, t);
    }

    public void flushLogEvent() {
        mDataTrack.flushLogEvent();
    }

    public String getChannelId() {
        return mChannel != null ? mChannel : CHANNEL_DEFAULT;
    }

    public String getDeviceId(String platform) {
        return mDataTrack.getDeviceId(platform);
    }

    public String getCarrier() {
        return DeviceInfoUtil.getCarrier(mContext);
    }
}